<?php
/*
 * @Description    : 通用
 * @Version        : 1.0.0
 * @Author         : QianLong
 * @Date           : 2021-04-17 09:01:53
 * @LastEditors    : QianLong
 * @LastEditTime   : 2023-07-07 17:53:15
 */

namespace app\api\controller;

use app\api\model\Manager;
use app\common\RedisCache;
use app\common\Verify;
use app\lib\Result;
use think\facade\Request;

class Common extends Base
{
  public function upload()
  {
    // 获取表单上传文件
    $files = request()->file();
    try {
      validate(['image' => 'filesize:10240|fileExt:jpg|image:200,200,jpg'])
        ->check($files);
      $savename = [];
      foreach ($files as $file) {
        $savename[] = \think\facade\Filesystem::putFile('topic', $file);
      }
    } catch (\think\exception\ValidateException $e) {
      echo $e->getMessage();
    }
  }
  public function uploadFile()
  {
    header('Content-Type:application/json; charset=utf-8');
    if (request()->isPost()) {
      $file = request()->file();
      $type = input('param.type');
      $info = validate(['image' => 'filesize:30720|fileExt:jpg,png,gif,jpeg,bmp,doc,docx,xls,xlsx,ppt,pptx,zip,rar,txt,mp4,avi,flv'])->check($file);
      if ($info) {
        //基于框架根目录的文件路径
        $savename = [];
        foreach ($file as $ins) {
          $item['url'] = \think\facade\Filesystem::disk('public')->putFile('topic', $ins);
          $item['name'] = $ins->getOriginalName();
          $savename[] = $item;
        }
        $fileUrls = [];
        $domain = Request::domain();
        foreach ($savename as $file) {
          $file['url'] = str_replace('\\','/', $file['url']);
          $fileUrls[] = $domain . '/storage/' . $file['url'];
        }
        $ossConfig = (new RedisCache())->getSysOssSetting();
        if ($ossConfig['open'] !== 1) {
          if ($type == 'wangeditor') {
            $return['errno'] = 0;
            $return['data'] = [];
            foreach ($fileUrls as $file) {
              $return['data'][] = ['url' => $file];
            }
          } else {
            $return['code'] = 200;
            $return['data'] = $fileUrls;
          }
        } else {
          $ossFileUrls = [];
          foreach ($savename as $sfile) {
            $sfile['url'] = str_replace('\\', '/', $sfile['url']);
            $fileD = new \Yurun\Util\YurunHttp\Http\Psr7\UploadedFile($sfile['name'], null, UPLOAD_PATH . $sfile['url']);
            $uploadResult = doFileUpload($fileD);
            if ($uploadResult['code'] == 200) {
              $ossFileUrls[] = $uploadResult['data']['url'];
            }
            unlink(UPLOAD_PATH . $sfile['url']);
          }
          if ($type == 'wangeditor') {
            $return['errno'] = 0;
            $return['data'] = [];
            foreach ($ossFileUrls as $file) {
              $return['data'][] = ['url' => $file];
            }
          } else {
            $return['code'] = 200;
            $return['data'] = $ossFileUrls;
          }
        }
        return json($return);
      } else {
        var_dump($info);
        var_dump($file);
      }
    }
  }
  public function uploadCrt()
  {
    header('Content-Type:application/json; charset=utf-8');
    if (request()->isPost()) {
      $file = request()->file();
      $info = validate(['application' => 'fileExt:crt'])->check($file);
      if ($info) {
        //基于框架根目录的文件路径
        $savename = [];
        foreach ($file as $ins) {
          $savename[] = \think\facade\Filesystem::disk('crt')->putFile('file', $ins);
        }
        return json(['code' => 200, 'data' => $savename[0], 'msg' => 'success']);
      } else {
        var_dump($info);
        var_dump($file);
        // 上传失败获取错误信息
      }
    }
  }
  /**
   * 获取验证码
   * @return void
   * @author QianLong <87498106@qq.com>
   * @date 2021-03-27 15:07:20
   * @editAuthor QianLong <87498106@qq.com>
   * @editDescription 
   * @editDate 2021-03-27 15:07:20
   */
  public function getSmsCode()
  {
    $phone = input('param.phone/s', '', 'trim');
    $type = input('param.type/s', '', 'trim');
    $ip = get_client_ip();
    if (empty($phone)) {
      return Result::Error('手机号不能为空');
    }
    if (checkphone($phone) != true) {
      return Result::Error('手机号格式不正确');
    }
    $dataVerify['token'] = input('param.token/s', '', 'trim');
    $dataVerify['authenticate'] = input('param.authenticate/s', '', 'trim');
    Verify::check($dataVerify);
    $has_phone = Manager::field('id')->where('phone', $phone)->where('id', $this->uid)->find();
    if ($type == 'change_phone_new') {
      if (!empty($has_phone)) {
        return Result::Error('该手机号已注册帐号，请更换手机号');
      }
    } else if ($type == 'change_phone_old') {
      if (empty($has_phone)) {
        return Result::Error('该手机号不正确，请确认后重试');
      }
    } else {
      if (empty($has_phone)) {
        return Result::Error('该手机号未注册帐号，请确认');
      }
    }

    if ($this->redis->ttl('sms_tj' . $ip) === -1) {
      $this->redis->del('sms_tj' . $ip);
    }
    if ($this->redis->exists('sms_tj' . $ip)) {
      $ipPhone = $this->redis->get('sms_tj' . $ip);
      if (($ipPhone > 5) && (!empty($ipPhone))) {
        return Result::Error('短信码获取频繁，请1小时后重试！');
      } else {
        $this->redis->incr('sms_tj' . $ip);
      }
    } else {
      $this->redis->set('sms_tj' . $ip, 1, 3600);
    }
    $smsCode = random_int(1000, 9999);
    $this->redis->set('smsCode:' . $phone, $smsCode, 600);
    $smsData['params_json'] = ['code' => $smsCode];
    $smsData['st_id'] = '';
    $smsData['phone'] = $phone;
    $sendResult = doSendSms($smsData);
    if (isset($sendResult['code']) && $sendResult['code'] == 200) {
      return Result::Success([], '发送成功');
    } else {
      return Result::Error('发送失败，请稍后重试 [Msg:' . $sendResult['msg'] . ']');
    }
  }
}
